#!/usr/bin/Python
# coding=utf-8
import getopt
import os
import signal
import sys
import traceback

import pytoml
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from thrift.transport import TSocket, TTransport

from extractor_proccessor import ExtractorProccessor
from i_util.logs import LogHandler

sys.path.append('..')
from i_util.thread_pool import ThreadPool
from i_util.input_thread import InputThread
from i_util.heart_beat import HeartbeatThread
from bdp.i_crawler.i_extractor import ExtractorService
from extractor import ExtractorHandler
from i_util.ProfilingUtil import profiler_creator
from i_util.ProfilingUtil import profiling_signal_handler

class ExtractorServer(object):
    def __init__(self, conf):
        self.conf = conf
        self.log = conf['log']
        thread_locals = {'processor': (ExtractorProccessor, (conf, 1)), 'profiler': (profiler_creator, ())}
        self.process_pool = ThreadPool(conf['server']['process_thread_num'], thread_locals)
        self.input_thread = InputThread(conf['beanstalk_conf'], conf['log'], self.process_pool)
        self.heartbeat_thread = HeartbeatThread("extractor", self.conf)
    def start(self):
        self.input_thread.start()
        self.heartbeat_thread.start()
        self.log.info("start ExtractorServer!")
    def stop(self,message):
        self.input_thread.stop()
        self.log.info("stop ExtractorServer %s!" %(message))



def main(conf):
    signal.signal(signal.SIGTERM, signal.SIG_DFL)
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    signal.signal(signal.SIGUSR1, lambda a, b : profiling_signal_handler("extractor", a, b))

    extract_server = ExtractorServer(conf)
    extract_server.start()

    try:
        handler = ExtractorHandler(conf)
        processor = ExtractorService.Processor(handler)
        transport = TSocket.TServerSocket(port=conf['server']['port'])
        tfactory = TTransport.TBufferedTransportFactory()
        pfactory = TBinaryProtocol.TBinaryProtocolFactory()
        server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
        server.setNumThreads(conf['server']['server_thread_num'])
        server.serve()
    except Exception, e:
        sys.stderr(traceback.format_exc())
        extract_server.stop("failt")
        os._exit(1)
    extract_server.stop("success")



if __name__ == '__main__':
    try:
        file_path='./extractor.toml'
        opt,args=getopt.getopt(sys.argv[1:],'f:',['help'])
        for name,value in opt:
            if name == "-f":
                file_path=value
            elif name in ("-h", "--help"):
                sys.exit()
            else:
                assert False, "unhandled option"
        config = None
        with open(file_path, 'rb') as config_file:
            config = pytoml.load(config_file)
        config['log']=LogHandler(config['server']['name']+str(config['server']['port']))
        main(config)
    except getopt.GetoptError:
        sys.exit()
